const fs = require('fs');
const path = require('path');
const scriptService = {
    async getScript(ctx) {
        return new Promise((resolve) => {
            const query = ctx.request.query;
            const keys = Object.keys(query);
            if (keys.length <= 0) {
                resolve("throw new Error('缺少参数');");
            }
            fs.readFile(path.resolve(__dirname, '../scripts/index.js'), 'utf-8', function (err, dataStr) {
                if (err) {
                    resolve("throw new Error('脚本出错');");
                } else {
                    let newStr = dataStr.replace(/\[siteToken\]/g, keys[0]);
                    newStr = newStr.replace(/\[domain\]/g, 'http://' + ctx.request.headers.host);
                    resolve(newStr);
                }
            });
        })
    }
};
module.exports = scriptService;